<?php

namespace library;

/**
 * Klasa opisująca obrazek
 *
 * @author Damian
 */
class Picture {

    public $formName;
    public $Name;
    public $Size;
    public $Mime;
    public $shopURL;
    public $fileName;
    public $width;
    public $height;

    public function __construct($formName, $shopURL) {
        $this->formName = $formName;
        $this->shopURL = substr($shopURL, 0, strlen($shopURL)-1);
        if (
                !isset($_FILES[$formName]['error']) ||
                is_array($_FILES[$formName]['error'])
        ) {
            throw new \RuntimeException(var_export($_FILES, true));
        }
        $this->chceckErrors();
        $this->Name = basename($_FILES[$this->formName]["name"]);
        $this->checkSize();
        $this->checkMime();
        $this->move();
    }

    public function chceckErrors() {
        switch ($_FILES[$this->formName]['error']) {
            case UPLOAD_ERR_OK:
                break;
            case UPLOAD_ERR_NO_FILE:
                throw new \RuntimeException('Nie wysłano żadnego pliku.');
            case UPLOAD_ERR_INI_SIZE:
            case UPLOAD_ERR_FORM_SIZE:
                throw new \RuntimeException('Przekroczony maksymalny rozmiar Pliku');
            default:
                throw new \RuntimeException('Wystąpił nieznany błąd');
        }
    }

    public function checkSize() {
        if ($_FILES[$this->formName]['size'] > 4*1024*1024) {
            throw new \RuntimeException('Przekroczony maksymalny dozowolny rozmiar pliku');
        }
        $this->Size = $_FILES[$this->formName]['size'];
    }

    public function checkMime() {
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        if (false === $ext = array_search(
                $finfo->file($_FILES[$this->formName]['tmp_name']), array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
                ), true
                )) {
            throw new \RuntimeException('Nierpawidłowy format pliku');
        }
        $this->Mime = $finfo->file($_FILES[$this->formName]['tmp_name']);
    }

    public function move() {
        $this->fileName = "img/" . $this->shopURL . "/" . $this->Name;
        if (!move_uploaded_file(
                        $_FILES[$this->formName]['tmp_name'], "img/" . $this->shopURL . "/big_" . $this->Name
                )) {
            throw new \RuntimeException('Nie udało się przenieść pliku na serwer');
        } else {
            $this->createThumb(128, 128);
        }
    }

    private function imageCreateFromAny($filepath) {
        $type = exif_imagetype($filepath);
        $allowedTypes = array(
            1, // [] gif 
            2, // [] jpg 
            3, // [] png 
            6   // [] bmp 
        );
        if (!in_array($type, $allowedTypes)) {
            return false;
        }
        switch ($type) {
            case 1 :
                $im = imageCreateFromGif($filepath);
                break;
            case 2 :
                $im = imageCreateFromJpeg($filepath);
                break;
            case 3 :
                $im = imageCreateFromPng($filepath);
                break;
            case 6 :
                $im = imageCreateFromBmp($filepath);
                break;
            default : throw new \RuntimeException('Nierpawidłowy format pliku');
        }
        return $im;
    }

    private function scale(&$image, $width, $height) {
        $this->width = imageSX($image);
        $this->height = imageSY($image);
        $thumb_w = $width;
        $thumb_h = $height;
        if ($this->width > $this->height) {
            $thumb_w = $width;
            $thumb_h = $this->height * ($height / $this->width);
        }
        if ($this->width < $this->height) {
            $thumb_w = $this->width * ($width / $this->height);
            $thumb_h = $height;
        }
        return ["width" => $thumb_w, "height" => $thumb_h];
    }

//    private function save(&$image, array $size) {
//        $dst_img = ImageCreateTrueColor($size["width"], $size["height"]);
//        imagecopyresampled($dst_img, $image, 0, 0, 0, 0, $size["width"], $size["height"], $this->width, $this->height);
//        imagejpeg($dst_img, "img/" . $this->shopURL . "/" . $this->Name);
//        imagedestroy($dst_img);
//        imagedestroy($image);
//        unlink("img/" . $this->shopURL . "/big_" . $this->Name);
//    }

    function createThumb($width, $height) {
        $image = $this->imageCreateFromAny("img/" . $this->shopURL . "/big_" . $this->Name);
       // $newImage = imagescale($image, $width, $height);
        $data = getimagesize("img/" . $this->shopURL . "/big_" . $this->Name);
        $width_old = $data[0];
        $height_old = $data[1];
        if ($width_old  >= $height_old) {
            $thumb_w = $width;
            $thumb_h = $height * ($height_old / $width_old);
        }
        else {
            $thumb_w = $width * ($width_old / $height_old);
            $thumb_h = $height;
        }
        $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
        imagecopyresampled($dst_img, $image, 0, 0, 0, 0, $thumb_w, $thumb_h, $width_old, $height_old);
        imagejpeg($dst_img, "img/" . $this->shopURL . "/".$width."px/" . $this->Name);
        imagedestroy($dst_img);
        imagedestroy($image);       
    }
    public function __destruct() {
        unlink("img/" . $this->shopURL . "/big_" . $this->Name);
    }

}
